package models

import (
	"github.com/myaccount/my-app/app/db"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type IPraisedCard interface {
	GetCardsByQid(qid string, limit int, obj interface{}) error
	Add(card Card) error
	RmId(id bson.ObjectId) error
}

type PraisedCard struct {
	Id      bson.ObjectId `bson:"_id" json:"cardId" valid:"Required"`
	Card    Card          `bson:"card" json:"card"`
	Qid     string        `bson:"qid" json:"qid" valid:"Required"`
	Created int64         `bson:"created" json:"created"`
}

func (this *PraisedCard) do(f func(*mgo.Collection) error) error {
	return db.DO("db_praisedcard", "praisedcard", f)
}

func (this *PraisedCard) GetCardsByQid(qid string, obj interface{}) error {
	return this.do(func(c *mgo.Collection) error {
		return c.Find(bson.M{"Qid": qid}).Hint("qid").All(obj)
	})
}

func (this *PraisedCard) Add(qid string, card Card) error {
	this.Created = time.Now().Unix()
	this.Card = card
	this.Id = card.Id
	this.Qid = qid
	return this.do(func(c *mgo.Collection) error {
		return c.Insert(this)
	})
}

func (this *PraisedCard) RmId(id bson.ObjectId) error {
	return this.do(func(c *mgo.Collection) error {
		return c.RemoveId(id)
	})
}
